package net.atomarrow.pr.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import net.atomarrow.ioc.ActionContext;
import net.atomarrow.pr.bean.PermissionBean;
import net.atomarrow.pr.domain.TbAccountRole;
import net.atomarrow.pr.domain.TbRole;
import net.atomarrow.pr.domain.TbRoleMenu;
import net.atomarrow.pr.staticvariable.PermissionSv;
import net.atomarrow.services.Service;

public class PermissionService extends Service {
	private AccountRoleService accountRoleService;
	private RoleMenuService roleMenuService;
	private RoleFuncService roleFuncService;
	private RoleService roleService;
	/**
	 * 加载所有角色的权限设置
	 */
	public void loadAllRoleConfig(){
		List<TbRole> roles = roleService.getAllRole();
		Map<Integer,Set<String>> roleFuncMap = new HashMap<Integer, Set<String>>();
		Map<Integer,List<TbRoleMenu>> roleMenuMap = new HashMap<Integer, List<TbRoleMenu>>();
		List<TbRoleMenu> roleMenus;
		for(TbRole role:roles){
		    roleMenus=roleMenuService.getByRoleId(role.getId());
			Set<String> set = roleFuncService.getRoleFuncSet(role.getId());
			set.addAll(roleMenuService.getRoleMenuSet(roleMenus));
			roleFuncMap.put(role.getId(), set);
			roleMenuMap.put(role.getId(), roleMenus);
		}
		ServletContext application = ActionContext.getContext().getApplication();
		application.setAttribute(PermissionSv.APPLICATION_KEY_PERMISSION_FUNC, roleFuncMap);
		application.setAttribute(PermissionSv.APPLICATION_KEY_PERMISSION_MENU, roleMenuMap);
	}
	
	/**
	 * 根据用户id加载权限
	 * @param accountId
	 */
	public void loadPermission(int accountId){
		List<TbAccountRole> roles = accountRoleService.getByAccountId(accountId);
		ServletContext application = ActionContext.getContext().getApplication();
		Map<Integer,Set<String>> roleFuncMap =(Map<Integer, Set<String>>) application.getAttribute(PermissionSv.APPLICATION_KEY_PERMISSION_FUNC);
		PermissionBean permissionBean = new PermissionBean();
		for(TbAccountRole accountRole:roles){
			permissionBean.addFunUrlSet(roleFuncMap.get(accountRole.getRoleId()));
			permissionBean.setRoleMenuMap((Map<Integer, List<TbRoleMenu>>) application.getAttribute(PermissionSv.APPLICATION_KEY_PERMISSION_MENU));
		}
		HttpSession session = ActionContext.getContext().getSession();
		session.setAttribute(PermissionSv.SESSION_KEY_PERMISSION_BEAN, permissionBean);
		session.setAttribute(PermissionSv.SESSION_KEY_PERMISSION_ROLE, roles);
	}
	
}
